package org.springframework.license.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Title LinuxComputerService
 * @Author zhijun.Guo
 * @Email tiankong061015@163.com
 * @Time 2024/9/2 20:42
 * @Description
 */
public class LinuxComputerService extends AbstractComputerService{
    /**
     * 获取IP地址
     *
     * @return ip
     */
    @Override
    public List<String> getIp() throws Exception {
        //获取所有网络接口
        List<InetAddress> inetAddresses = getLocalAllInetAddress();

        if(CollectionUtils.isEmpty(inetAddresses)) return null;

        return inetAddresses.stream().map(InetAddress::getHostAddress).distinct().map(String::toLowerCase)
                .collect(Collectors.toList());

    }

    /**
     * 获取MAC地址
     *
     * @return MAC
     */
    @Override
    public List<String> getMac() throws Exception {
        List<InetAddress> inetAddresses = getLocalAllInetAddress();
        if(CollectionUtils.isEmpty(inetAddresses)) return null;
        return inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList());
    }

    /**
     * 获取CPU型号
     *
     * @return CPU
     */
    @Override
    public String getCpu() throws IOException {
        //序列号
        String serialNumber = "";

        //使用dmidecode命令获取CPU序列号
        String[] shell = {"/bin/bash","-c","dmidecode -t processor | grep 'ID' | awk -F ':' '{print $2}' | head -n 1"};
        Process process = Runtime.getRuntime().exec(shell);
        process.getOutputStream().close();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line = reader.readLine();
        if(StringUtils.isNotBlank(line)){
            serialNumber = line.trim();
        }

        reader.close();
        return serialNumber;

    }

    /**
     * 获取主板型号
     *
     * @return 主板型号
     */
    @Override
    public String getMain() throws IOException {
        //序列号
        String serialNumber = "";

        //使用dmidecode命令获取主板序列号
        String[] shell = {"/bin/bash","-c","dmidecode | grep 'Serial Number' | awk -F ':' '{print $2}' | head -n 1"};
        Process process = Runtime.getRuntime().exec(shell);
        process.getOutputStream().close();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line = reader.readLine();
        if(StringUtils.isNotBlank(line)){
            serialNumber = line.trim();
        }

        reader.close();
        return serialNumber;

    }
}
